import store from '../../store/index'
export default class SocketService {
  // 单例
  static instance = null
  static get Instance () {
    if (!this.instance) {
      this.instance = new SocketService()
    }
    return this.instance
  }

  // 和服务端服务器连接的socket对象
  ws = null
  // 是否已经连接成功
  isConnection = false
  // 记录重连此数
  times = 0
  // 重新发送
  retrySend = 0
  // 主动关闭连接
  isActive = false
  // 连接方法
  connect () {
    if (!window.WebSocket) {
      return alert('您的浏览器不支持WebSocket')
    }
    this.ws = new WebSocket('ws://localhost:3001')
    // this.ws = new WebSocket('ws://172.30.105.199:3001')
    this.ws.onopen = () => {
      this.isConnection = true
      this.send({ tower: window.localStorage.getItem('tower') })
    }
    this.ws.onclose = () => {
      if (!this.isActive) {
        this.isConnection = false
        console.log('正在尝试重新连接')
        this.times++
        setTimeout(() => {
          this.connect()
        }, this.times * 500)
      } else {
        console.log('主动关闭连接')
      }
    }
    this.ws.onmessage = this.getData
  }

  // 发送数据
  send (data) {
    if (this.isConnection) {
      this.ws.send(JSON.stringify(data))
    } else {
      setTimeout(() => {
        this.ws.send(JSON.stringify(data))
      }, this.retrySend * 500)
    }
  }

  // 接收数据
  getData (data) {
    // console.log('接收到数据')
    const informData = data.data
    store.dispatch('websocketdata/get_data', informData)
  }

  // 关闭连接
  close () {
    this.isActive = true
    this.ws.close()
  }
}
